<template>
    <div>
        <div class="flex justify-between mb-2.5 text-sm">
            <p>默认用户设置</p>
        </div>
        <el-table :data="tableData" v-if="domainEdit">
            <el-table-column prop="name" label="用户名"></el-table-column>
            <el-table-column prop="stuffName" label="用户组"></el-table-column>
            <el-table-column prop="createdAt" label="上次更新时间"></el-table-column>
            <el-table-column prop="locked" label="用户状态"></el-table-column>
            <el-table-column label="设置">
                <el-button @click="editUser">编辑</el-button>
            </el-table-column>
        </el-table>
        <div class="domain-edit" v-if="!domainEdit">
            <el-form
                ref="domainFormRef"
                :rules="rules"
                label-width="175px"
                :model="domainDataObj"
                >
                <el-form-item label="默认管理员">
                    {{ domainDataObj.user }}
                </el-form-item>
                <el-form-item label="管理员密码" prop="pwd">
                    <el-input v-model="domainDataObj.pwd" style="width: 240px" type="password" autocomplete="new-password"/>
                    <span class="ml-2.5">必须是字母、数字组合，可以加入特殊符号（!@#S%^&"），长度在8到25位之间</span>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPwd">
                    <el-input v-model="domainDataObj.confirmPwd" style="width: 240px" type="password" autocomplete="new-password"/>
                </el-form-item>
                <el-form-item label="管理员状态">
                    <el-switch v-model="domainDataObj.adminStatus" class="switch-color"
                        inline-prompt
                        active-text="锁定"
                        inactive-text="解锁"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="domainSubmit" :disabled="domainDataObj.pwd == ''">确定</el-button>
                    <el-button  @click="cancelSubmit">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { 
    req_getDefaultDomains,
    req_setUserLock, 
    req_setInitdomain 
} from "~/utils/axios/setting.js";
import moment from "moment";
/****************表格数据处理********************/ 
let tableData = reactive([
    {name: '', stuffName: '', createdAt: '', locked: '',}
])
let userData = {}
const initDomain = () => {
    req_getDefaultDomains().then(res => {
        if(res.data.length <= 0){
            domainEdit.value = false;
            return
        }else{
            domainEdit.value = true;
        }
        userData = res.data[0].user
        tableData[0].name = userData.name;
        tableData[0].stuffName = userData.stuffName;
        tableData[0].createdAt = moment(userData.createdAt).format("YYYY-MM-DD HH:mm:ss");
        tableData[0].locked = userData.locked ? '锁定' : '解锁';
    })
}
initDomain()
/********************表格完成***************************/
/********************编辑状态***************************/
let domainEdit = ref(false)
let domainFormRef = ref()
let domainDataObj = reactive({
    user: 'admin',
    pwd: '',
    confirmPwd: '',
    adminStatus: false
})
const rules = reactive({
    pwd: [{ required: true, message: '', trigger: 'blur' },
        {
        validator: (rule, value, callback) => {
            // 自定义验证规则
            const regex = /^[A-Za-z0-9!@#\$%\^&\*()_+={}\[\]|\\:;"'<>,.?/~`-]{8,25}$/;
            if (!regex.test(value)) {
            callback(new Error('必须是字母、数字组合，可以加入特殊符号（!@#S%^&"），长度在8到25位之间'));
            } else {
            callback();
            }
        },
        trigger: 'blur'
        }
    ],
    confirmPwd: [{ required: true, message: '', trigger: 'blur' },
        {
        validator: (rule, value, callback) => {
            if (value != domainDataObj.pwd) {
                callback(new Error('密码不一致，请再次确认'));
            } else {
                callback();
            }
        },
        trigger: 'blur'
    }]
});
const editUser = async () => {
    domainEdit.value = false;
}
const domainSubmit = () => {
    domainFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            domainEdit.value = false;
            let initdomainParam = {
                "user":{
                    "name": "admin",
                    "passwordHash": domainDataObj.confirmPwd,
                    "stuffName": "",
                    "locked": domainDataObj.adminStatus
                },
                "domainInfo":{
                    "domainName": "default",
                    "domainCode": "default",
                    "isMultiDomains": false
                }
            }
            req_getDefaultDomains().then(res => {
                if(res.data.length <= 0){
                    req_setInitdomain(initdomainParam).then(res => {
                        initDomain()
                    },error => {
                        domainEdit.value = true;
                    })
                }else{
                    req_setUserLock(domainDataObj.adminStatus ? 'lock' : 'unlock').then(res => {
                        initDomain()
                    },error => {
                        domainEdit.value = true;
                    })
                }
            })
        }
    });
}
const cancelSubmit = () => {
    domainEdit.value = true;
    domainDataObj.pwd = '';
    domainDataObj.confirmPwd = '';
    domainDataObj.adminStatus = false;
}
</script>

<style lang="scss" scoped>
.domain-edit{
    background-color: #fff;
    color: #555;
    padding: 10px;
    border-radius: 3px;
    box-shadow: 0px 2px 4px 0px rgba(64, 32, 224, 0.06);
}
:deep(.switch-color span[aria-hidden="true"]){
    .is-text{
        color: #000;
    }
}
</style>